<template>
  <div ref="chart02" class="chart-1"></div>
</template>
<script>
import * as echarts from 'echarts';
export default {
  data() {
    return {
      myEcharts: null,
      option: {
        title: {
          text: '商家销售统计',
          textStyle: {
            color: '#fff',
            fontSize: 15
          },
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },  
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          boundaryGap: [0, 0.1]
        },
        yAxis: {
          type: 'category',
          data: []
        },
        series: [
          {
            type: 'bar',
            label: {
              show: true,
              position: 'right'
            },
            barwidth: 10,
            data: [],
            itemStyle: {
              color: {
                x: 0,
                y: 0,
                x2: 1,
                y2: 0.5,
                type: 'linear',
                colorStops: [{
                  offset: 0,
                  color: '#A86DE5'
                }, {
                  offset: 1,
                  color: '#5153EE'
                }]
              },
              borderRadius: [0, 20, 20, 0]
            },
          }
        ],
      },
      ws: null,
      page: 1
    };
  },

  methods: {
    getData() {
      this.ws = new WebSocket("ws://127.0.0.1:9998")
      this.ws.onopen = () => {
        console.log("WebSocket连接已建立");
        //发送数据
        let params = {
          action: 'getData',
          socketType: 'sellerData',
          chartName: 'seller',
          value: ''
        }
        //发送
        this.ws.send(JSON.stringify(params));
        //接收
        this.ws.onmessage = (e) => {
          let data = JSON.parse(e.data);
          let sellers= JSON.parse(data.data);
          let Total = Math.ceil(sellers.length / 5);
          sellers.sort((a, b) => b.value - a.value);
          let list = sellers.slice((this.page-1) * 5, this.page * 5);
          this.option.yAxis.data = list.map(item => item.name).sort((a,b)=>a-b);
          this.option.series[0].data = list.map(item => item.value).sort((a,b)=>a-b);
          this.myEcharts.setOption(this.option);
          this.page++;
          if (this.page > Total) {
            this.page = 1;
          }   
        }
      };
    }
  },
  mounted() {

    // 基于准备好的dom，初始化echarts实例
    this.myEcharts = echarts.init(this.$refs['chart02']);
    //关联
    this.myEcharts.setOption(this.option);
    this.getData()
  }
}
</script>
<style scoped>
.chart-1 {
  height: 100%;
}
</style>